package com.onlinescxhz.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.onlinescxhz.demo.service.GoodsSPUServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传接口
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String fileuploadpath;
    @Value("${files.upload.ip}")
    private  String ip;
    @Resource
    private GoodsSPUServiceImpl goodsSPUService;
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        //原文件名
        String originname = file.getOriginalFilename();
        //文件类型
        String type = FileUtil.extName(originname);

         //文件路经
        File uploadParentfile = new File(fileuploadpath);
        if(!uploadParentfile.exists()){
            uploadParentfile.mkdirs();
        }
        //定义文件唯一的标识码 路径 文件名 type
        String uid = IdUtil.fastSimpleUUID();
        String imgfilenametype= uid + "." +type;
        String savepath=fileuploadpath + imgfilenametype;

        File uploadFile = new File(savepath);

        //String url= "http://localhost:8089/file/"+imgfilenametype;
        String url= "http://"+ip+":8089/file/"+imgfilenametype;
        //存储到磁盘
        file.transferTo(uploadFile);
        //goodsSPUService.save(new GoodsSPU(0,url));
        return url;
    }
    /**
     * 文件下载接口   http://localhost:8089/file/{fileUUID}
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileuploadpath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}
